package com.mhtool.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author yin
 * @date 2022/1/26 9:40
 * @since 3.8.0
 */
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
    public static final String ACTIVE_PROFILE_PROD = "prod";
    public static final String ACTIVE_PROFILE_DEV = "dev";
    public static final String ACTIVE_PROFILE_LOCAL = "local";
    public static final String ACTIVE_PROFILE_TEST = "test";
    static ApplicationContext context;
    public static ApplicationContext getContext() {
        if (context == null) {
            throw new IllegalStateException("applicaitonContext未注入");
        }
        return context;
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtils.context = applicationContext;
    }
    public static <T> T getBean(Class<T> requiredType) {
        return context.getBean(requiredType);
    }
    public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return context.getBean(name, requiredType);
    }

    /**
     * @param type 接口类
     * @return 所有实现类的beanName
     */
    public static String[] getBeanNamesForType(@Nullable Class<?> type) {
        return context.getBeanNamesForType(type);
    }

    /**
     * @param type 接口类
     * @return Map<beanName, bean>
     */
    public static <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException {
        return context.getBeansOfType(type);
    }

    public static String getActiveProfile() {
        return context.getEnvironment().getActiveProfiles()[0];
    }
}